// 数据上传页面的JavaScript逻辑

document.addEventListener('DOMContentLoaded', function() {
    console.log('数据上传页面已加载');
    
    // 初始化上传表单
    initUploadForm();
    
    // 加载已上传数据信息
    loadUploadedDataInfo();
});

// 初始化上传表单
function initUploadForm() {
    const form = document.getElementById('upload-form');
    form.addEventListener('submit', handleFileUpload);
    
    // 初始化清除数据按钮
    const clearBtn = document.getElementById('clear-data');
    clearBtn.addEventListener('click', clearAllData);
}

// 处理文件上传
async function handleFileUpload(event) {
    event.preventDefault();
    
    const fileType = document.getElementById('file-type').value;
    const fileInput = document.getElementById('data-file');
    const file = fileInput.files[0];
    
    if (!fileType || !file) {
        showUploadStatus('请选择文件类型和文件', 'error');
        return;
    }
    
    try {
        showUploadStatus('正在上传文件...', 'info');
        
        // 创建FormData对象
        const formData = new FormData();
        formData.append('file_type', fileType);
        formData.append('file', file);
        
        // 发送上传请求
        const response = await fetch(CONFIG.API_BASE_URL + '/upload', {
            method: 'POST',
            body: formData
        });
        
        if (!response.ok) {
            throw new Error(`上传失败: ${response.status}`);
        }
        
        const result = await response.json();
        
        if (result.status === 'success') {
            showUploadStatus('文件上传成功: ' + result.message, 'success');
            // 重新加载已上传数据信息
            loadUploadedDataInfo();
            // 清空表单
            document.getElementById('upload-form').reset();
        } else {
            showUploadStatus('上传失败: ' + result.message, 'error');
        }
    } catch (error) {
        console.error('上传文件失败:', error);
        showUploadStatus('上传失败: ' + error.message, 'error');
    }
}

// 加载已上传数据信息
async function loadUploadedDataInfo() {
    try {
        const response = await fetch(CONFIG.API_BASE_URL + '/data/info');
        
        if (!response.ok) {
            throw new Error(`获取数据信息失败: ${response.status}`);
        }
        
        const dataInfo = await response.json();
        updateDataInfoDisplay(dataInfo);
    } catch (error) {
        console.error('加载数据信息失败:', error);
        document.getElementById('data-info').innerHTML = '<p>加载数据信息失败: ' + error.message + '</p>';
    }
}

// 更新数据信息显示
function updateDataInfoDisplay(dataInfo) {
    const container = document.getElementById('data-info');
    
    if (Object.keys(dataInfo).length === 0) {
        container.innerHTML = '<p>暂无已上传数据</p>';
        return;
    }
    
    let html = `
        <table class="data-info-table">
            <thead>
                <tr>
                    <th>文件类型</th>
                    <th>文件路径</th>
                    <th>文件大小</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    for (const [fileType, info] of Object.entries(dataInfo)) {
        html += `
            <tr>
                <td>${fileType}</td>
                <td>${info.file_path || 'N/A'}</td>
                <td>${info.size_kb ? info.size_kb + ' KB' : 'N/A'}</td>
                <td>${info.error ? '错误: ' + info.error : '正常'}</td>
            </tr>
        `;
    }
    
    html += `
            </tbody>
        </table>
    `;
    
    container.innerHTML = html;
}

// 清除所有数据
async function clearAllData() {
    if (!confirm('确定要清除所有已上传的数据吗？此操作不可恢复。')) {
        return;
    }
    
    try {
        const response = await fetch(CONFIG.API_BASE_URL + '/data/clear', {
            method: 'DELETE'
        });
        
        if (!response.ok) {
            throw new Error(`清除数据失败: ${response.status}`);
        }
        
        const result = await response.json();
        
        if (result.status === 'success') {
            alert('数据清除成功');
            // 重新加载已上传数据信息
            loadUploadedDataInfo();
        } else {
            alert('数据清除失败: ' + result.message);
        }
    } catch (error) {
        console.error('清除数据失败:', error);
        alert('清除数据失败: ' + error.message);
    }
}

// 显示上传状态
function showUploadStatus(message, type) {
    const statusDiv = document.getElementById('upload-status');
    statusDiv.textContent = message;
    statusDiv.className = 'upload-status ' + type;
    statusDiv.classList.remove('hidden');
    
    // 3秒后自动隐藏成功或信息提示
    if (type === 'success' || type === 'info') {
        setTimeout(() => {
            statusDiv.classList.add('hidden');
        }, 3000);
    }
}